import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { getUserMenus } from '@/api/menu'

// 路由组件
const Layout = () => import('@/layout/index.vue')
const Login = () => import('@/views/Login.vue')
const Dashboard = () => import('@/views/Dashboard.vue')
const TestTools = () => import('@/views/TestTools.vue')
const Analysis = () => import('@/views/Analysis.vue')
const ApiAutomation = () => import('@/views/ApiAutomation.vue')
const UiAutomation = () => import('@/views/UiAutomation.vue')
const UserManagement = () => import('@/views/UserManagement.vue')

const Requirements = () => import('@/views/Requirements.vue')

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'test-tools',
        name: 'TestTools',
        component: TestTools,
        meta: { title: '测试工具', icon: 'Tools' }
      },
      {
        path: 'analysis',
        name: 'Analysis',
        component: Analysis,
        meta: { title: 'AI助手', icon: 'Cpu' }
      },
      {
        path: 'api-automation',
        name: 'ApiAutomation',
        component: ApiAutomation,
        meta: { title: '接口自动化', icon: 'Connection' }
      },
      {
        path: 'ui-automation',
        name: 'UiAutomation',
        component: UiAutomation,
        meta: { title: 'UI自动化', icon: 'Monitor' }
      },
      {
        path: 'user-management',
        name: 'UserManagement',
        component: UserManagement,
        meta: { title: '用户权限', icon: 'User' }
      },
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: { title: '仪表盘', icon: 'DataBoard' }
      },

      {
        path: 'requirements',
        name: 'Requirements',
        component: Requirements,
        meta: { title: '需求管理', icon: 'Document' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  
  // 检查是否需要认证
  if (to.meta.requiresAuth !== false && !authStore.isAuthenticated) {
    next('/login')
    return
  }
  
  // 如果已登录但访问登录页，重定向到首页
  if (to.path === '/login' && authStore.isAuthenticated) {
    next('/')
    return
  }
  
  // 如果已认证且不是登录页，检查菜单权限
  if (authStore.isAuthenticated && to.path !== '/login') {
    try {
      const response = await getUserMenus()
      if (response && response.data && response.data.success) {
        const allowedPaths = response.data.data.menus.map(menu => menu.path)
        
        // 检查当前路径是否在允许的菜单中
        if (!allowedPaths.includes(to.path)) {
          // 如果当前路径不被允许，重定向到第一个允许的菜单
          const firstAllowedPath = allowedPaths[0] || '/dashboard'
          next(firstAllowedPath)
          return
        }
      }
    } catch (error) {
      console.error('检查菜单权限失败:', error)
      // 如果权限检查失败，允许访问（避免阻断用户）
    }
  }
  
  next()
})

export default router 